<?php

namespace catchAdmin\archives\controller;

use app\common\business\Patient;
use app\common\model\PatientInfo;
use catcher\CatchResponse;
use catcher\base\CatchRequest;
use catcher\base\CatchController;
use catcher\exceptions\FailedException;
use catcher\exceptions\ValidateFailedException;


class TargetData extends CatchController
{
    protected \app\common\model\TargetData $model;

    public function __construct(\app\common\model\TargetData $targetData)
    {
        $this->model = $targetData;
    }

    /**
     * 列表
     *
     * @time 2020年01月09日
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     */
    public function index(CatchRequest $request): \think\response\Json
    {
        $patientId = $request->param("patient_id", "", "string");
        if (empty(trim($patientId))) {
            throw new ValidateFailedException("患者id不能为空");
        }
        return CatchResponse::paginate($this->model->getLists($patientId));
    }

    /**
     * 保存
     *
     * @time 2020年01月09日
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function save(CatchRequest $request): \think\response\Json
    {
        $postData = $request->param();
        if (!isset($postData["patient_id"])) {
            throw new ValidateFailedException("患者id不能为空");
        }
        //根据患者id获取患者信息
        $patientInfo = (new PatientInfo())->getPatientInfo($postData["patient_id"], 1);

        if (empty($patientInfo)) {
            throw new FailedException("患者信息不存在");
        }
        $postData["creator_id"] = $request->user()->id;
        $postData["creator_name"] = $request->user()->username;
        return CatchResponse::success($this->model->save($postData));
    }

    /**
     * 更新
     *
     * @time 2020年01月09日
     * @param $id
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function read($id, CatchRequest $request): \think\response\Json
    {
        $result = $this->model->findOrEmpty($id);

        return CatchResponse::success($result);
    }

    /**
     * 更新
     *
     * @time 2020年01月09日
     * @param $id
     * @param CatchRequest $request
     * @return \think\response\Json
     */
    public function update($id, CatchRequest $request): \think\response\Json
    {
        return CatchResponse::success($this->model->updateBy($id, $request->param()));
    }

    /**
     * 删除
     *
     * @time 2020年01月09日
     * @param $id
     * @return \think\response\Json
     */
    public function delete($id): \think\response\Json
    {
        return CatchResponse::success($this->model->destroy($id));
    }
}